/**
 * Copyright (c) 2016-2020 https://github.com/zhaohuatai
 *
 * contact 824069438@qq.com
 *  
 */
package org.zfes.snowy.ss.config.configrations;

import org.apache.catalina.core.AprLifecycleListener;
import org.apache.coyote.AbstractProtocol;
import org.apache.coyote.http11.Http11AprProtocol;
import org.apache.coyote.http11.Http11NioProtocol;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.embedded.ConfigurableEmbeddedServletContainer;
import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer;
import org.springframework.boot.context.embedded.tomcat.TomcatConnectorCustomizer;
import org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.zfes.snowy.ss.config.properties.TomcatConfigProperties;
import org.apache.catalina.connector.Connector;  
@Configuration
public class TomcatConfigration {
	@Autowired
	private TomcatConfigProperties tomcatConfigProperties;
	
	AprLifecycleListener arpLifecycle = null;
	@Bean  
	public EmbeddedServletContainerCustomizer createEmbeddedServletContainerCustomizer(){  
	    return new MyEmbeddedServletContainerCustomizer();  
	}  
	private class MyEmbeddedServletContainerCustomizer implements EmbeddedServletContainerCustomizer{  
	     public void customize(ConfigurableEmbeddedServletContainer container){  
	         TomcatEmbeddedServletContainerFactory tomcatFactory = (TomcatEmbeddedServletContainerFactory)container;  
	         if (tomcatConfigProperties.getEnableApr()) {
	             arpLifecycle = new AprLifecycleListener();    
	             tomcatFactory.setProtocol("org.apache.coyote.http11.Http11AprProtocol");
	             tomcatFactory.addConnectorCustomizers(new MyTomcatConnectorCustomizer()); 
	         }
	     }  
	 }
	
	private class MyTomcatConnectorCustomizer implements TomcatConnectorCustomizer{  
	    public void customize(Connector connector) {  
	    	AbstractProtocol<?> protocol=(AbstractProtocol<?>) connector.getProtocolHandler(); 
	    	if(tomcatConfigProperties.getEnableApr()){
	    		 protocol = (Http11AprProtocol) connector.getProtocolHandler(); 
	    	}else{
	    		 protocol = (Http11NioProtocol) connector.getProtocolHandler();  
	    	}
	    	protocol.getAddress();
	    }  
	}  
	
}